using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using PackTracker.Business;

namespace PackTracker.UserControls
{
	public partial class VeiculoEditar : UserControl
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				veiculoForm.DefaultMode = getVeiculo().IsNew ? FormViewMode.Edit : FormViewMode.ReadOnly;
				ApplyAuthorizationRules();
			}
		}

		#region Metodos privados

		private void ApplyAuthorizationRules()
		{
			//veiculoButton.Visible = PackTracker.Business.Veiculo.CanAddObject();
		}

		private void setVeiculo(Veiculo veiculo, bool salvar)
		{
			if (salvar)
			{
				veiculo = veiculo.Save();
				ViewState["Veiculo"] = Veiculo.GetVeiculo(veiculo.Id);
			}
			else
			{
				ViewState["Veiculo"] = veiculo;
			}
		}

		protected Veiculo getVeiculo()
		{
			int veiculoId = 0;
			Veiculo veiculo = ViewState["Veiculo"] as Veiculo;

			if (veiculo == null)
			{
				if (!String.IsNullOrEmpty(Request.QueryString["VeiculoId"]))
					int.TryParse(Request.QueryString["VeiculoId"].ToString(), out veiculoId);

				veiculo = (veiculoId == 0) ? Veiculo.NewVeiculo() : Veiculo.GetVeiculo(veiculoId);
				ViewState.Add("Veiculo", veiculo);
			}
			return veiculo;
		}

		#endregion

		#region VeiculoForm

		protected void veiculoForm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
		{
			Veiculo veiculo = getVeiculo();
			Csla.Data.DataMapper.Map(e.NewValues, veiculo, "Id");
			setVeiculo(veiculo, true);
			
			veiculoForm.DefaultMode = FormViewMode.ReadOnly;
            veiculoForm.DataBind();
		}
		
        protected void veiculoForm_ItemCommand(object sender, FormViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Cancel":
                    veiculoForm.DefaultMode = FormViewMode.ReadOnly;
                    veiculoForm.DataBind();
                    break;
                case "Edit":
                    veiculoForm.DefaultMode = FormViewMode.Edit;
                    ApplyAuthorizationRules();
                    break;
            }
        }
        
        protected void veiculoForm_ItemDeleting(object sender, FormViewDeleteEventArgs e)
        {
            Veiculo.DeleteVeiculo(getVeiculo().Id);
        }
		
		#endregion
		
		#region DataSources

		protected void veiculoDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
		{
			e.BusinessObject = getVeiculo();
		}

		protected void idMotoristaListDataSource_SelectObject(object sender, Csla.Web.SelectObjectArgs e)
		{
			e.BusinessObject = FuncionarioCollection.GetFuncionarioCollection();
		}

		#endregion
		
    }
}
